const sequelize = require('@shared/utils/database');
const User = require('./user');
const Product = require('./product');
const Category = require('./category');
const Cart = require('./cart');
const Admin = require('./admin');
const Banner = require('./banner');
const Address = require('./address');
const Order = require('./order');
const OrderItem = require('./order-item');
const Payment = require('./payment');

// 设置关联关系
// 分类与商品的关联 (一对多)
Category.hasMany(Product, {
  foreignKey: 'category_id',
  as: 'products'
});

Product.belongsTo(Category, {
  foreignKey: 'category_id',
  as: 'category'
});

// 用户 - 地址
User.hasMany(Address, { 
  foreignKey: 'user_id', 
  constraints: false
});

Address.belongsTo(User, { 
  foreignKey: 'user_id',
  constraints: false
});

// 用户 - 购物车
User.hasMany(Cart, { 
  foreignKey: 'user_id',
  constraints: false
});

Cart.belongsTo(User, { 
  foreignKey: 'user_id',
  constraints: false
});

// 商品 - 购物车
Product.hasMany(Cart, { 
  foreignKey: 'product_id',
  constraints: false
});

Cart.belongsTo(Product, { 
  foreignKey: 'product_id',
  constraints: false
});

// 用户 - 订单
User.hasMany(Order, { 
  foreignKey: 'user_id',
  as: 'orders',
  constraints: false
});

Order.belongsTo(User, { 
  foreignKey: 'user_id',
  as: 'user',
  constraints: false
});

// 订单 - 订单商品
Order.hasMany(OrderItem, { 
  foreignKey: 'order_id',
  as: 'items',
  constraints: false
});

OrderItem.belongsTo(Order, { 
  foreignKey: 'order_id',
  constraints: false
});

// 商品 - 订单商品
Product.hasMany(OrderItem, { 
  foreignKey: 'product_id',
  constraints: false
});

OrderItem.belongsTo(Product, { 
  foreignKey: 'product_id',
  constraints: false
});

// 订单 - 支付记录
Order.hasMany(Payment, { 
  foreignKey: 'order_id',
  constraints: false
});

Payment.belongsTo(Order, { 
  foreignKey: 'order_id',
  constraints: false
});

// 组装所有模型
const models = {
  User,
  Product,
  Category,
  Cart,
  Admin,
  Banner,
  Address,
  Order,
  OrderItem,
  Payment,
  sequelize // 导出sequelize实例
};

// 同步数据库模型到数据库
// 开发和测试环境下才会自动同步
if (process.env.SYNC_DB === 'true') {
  const forceDrop = process.env.FORCE_SYNC === 'true';
  sequelize.sync({ force: forceDrop }).then(() => {
    console.log(`数据库同步${forceDrop ? '(强制)' : ''}完成`);
  }).catch(err => {
    console.error('数据库同步失败:', err);
  });
} else {
  console.log('数据库同步已禁用');
}

module.exports = models; 